package com.example.springboot.service;

/**
 * @author yuwl
 * @description
 * @since 2024-05-22 15:36
 */
import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;

@Service
public class PDFParserService {
    public String parsePDF(String filePath) throws IOException {
        // 仅内存加载文档，可能会内存溢出
        PDDocument document = PDDocument.load(new File(filePath));
        PDFTextStripper stripper = new PDFTextStripper();
        String text = stripper.getText(document);
        document.close();
        return text;
    }

    public String parsePDFMix(String filePath) throws IOException {
        // 使用内存限制设置加载文档，在内存中使用的最大字节数，超过此限制后使用临时文件。
        MemoryUsageSetting memUsageSetting = MemoryUsageSetting.setupMixed(50 * 1024 * 1024); // 设置内存限制为50MB
        try (PDDocument document = PDDocument.load(new File(filePath), memUsageSetting)) {
            PDFTextStripper pdfStripper = new PDFTextStripper();
            return pdfStripper.getText(document);
        }
    }
}
